package com.shuaiche.yeguan;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.google.gson.Gson;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.MerchantConfigModel;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.ui.upload.CarPictureAdapter;
import com.shuaiche.yeguan.util.DensityUtils;
import com.shuaiche.yeguan.util.DeviceHelper;
import com.shuaiche.yeguan.util.FileUtils;
import com.shuaiche.yeguan.util.SPUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.brandselectbar.ItemBean;
import com.shuaiche.yeguan.views.dialog.LoadingDialog;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends ReactActivity {
    public static final int REQUEST_FRA_SCANNING = 1000;//VIN扫描
    public static final int REQUEST_SELECT_BRAND = 1001;//选择品牌
    public static final int REQUEST_UPLOAD_CHECK_REPORT = 1002;//上传检测报告
    public static final int REQUEST_SELECT_FILE = 1003;//上传文件
    public static final int REQUEST_UPLOAD_CONTRACT = 1004;//上传合同文件

    private String imFilePath;
    private LoadingDialog loadingDialog;
    private Uri fileUri;

    /**
     * Returns the name of the main component registered from JavaScript. This is used to schedule
     * rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "Shuaicheyeguan";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        getWindow().getDecorView().setSystemUiVisibility(
//                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//        );

        super.onCreate(null);

        getMerchantConfig();
    }

    /**
     * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
     * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
     * (aka React 18) with two boolean flags.
     */
//  @Override
//  protected ReactActivityDelegate createReactActivityDelegate() {
//    return new DefaultReactActivityDelegate(
//        this,
//        getMainComponentName(),
//        // If you opted-in for the New Architecture, we enable the Fabric Renderer.
//        DefaultNewArchitectureEntryPoint.getFabricEnabled());
//  }
    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected Bundle getLaunchOptions() {
                Bundle bundle = new Bundle();

                int apiType = SPUtils.getInt(getApplicationContext(), SPUtils.API_TYPE, 0);
                boolean isDebug = BuildConfig.DEBUG;
                if (isDebug){
                    if (apiType == 0 || apiType == 1) {
                        bundle.putString("apiDomain", SCAppConfig.BASE_URL_DEV);
                        bundle.putString("webDomain", SCAppConfig.BASE_H5_DEV);
                        bundle.putString("imApiAddr", SCAppConfig.BASE_IM_DEV);
                        bundle.putString("imWsAddr", SCAppConfig.BASE_IM_WS_DEV);
                    } else if (apiType == 2) {
                        bundle.putString("apiDomain", SCAppConfig.BASE_URL_TEST);
                        bundle.putString("webDomain", SCAppConfig.BASE_H5_TEST);
                        bundle.putString("imApiAddr", SCAppConfig.BASE_IM_TEST);
                        bundle.putString("imWsAddr", SCAppConfig.BASE_IM_WS_TEST);
                    } else if (apiType == 3) {
                        bundle.putString("apiDomain", SCAppConfig.BASE_URL_RELEASE);
                        bundle.putString("webDomain", SCAppConfig.BASE_H5_RELEASE);
                        bundle.putString("imApiAddr", SCAppConfig.BASE_IM_RELEASE);
                        bundle.putString("imWsAddr", SCAppConfig.BASE_IM_WS_RELEASE);
                    }

                    bundle.putBoolean("release", false);
                }else {
                    bundle.putString("apiDomain", SCAppConfig.BASE_URL_RELEASE);
                    bundle.putString("webDomain", SCAppConfig.BASE_H5_RELEASE);
                    bundle.putString("imApiAddr", SCAppConfig.BASE_IM_RELEASE);
                    bundle.putString("imWsAddr", SCAppConfig.BASE_IM_WS_RELEASE);
                    bundle.putBoolean("release", true);
                }

//                System.out.println("apiDomain>>>>>>>>>:"+SCAppConfig.BASE_URL_TEST);

                bundle.putInt("apiType",apiType);

                if (SCUserInfoConfig.getUserinfo() != null) {
                    if (SCUserInfoConfig.getUserinfo().getSessionId() != null) {
                        bundle.putString("sessionId", SCUserInfoConfig.getUserinfo().getSessionId());
                    }
                    bundle.putString("userId", SCUserInfoConfig.getUserinfo().getUserId() + "");
                    bundle.putString("merchantId", SCUserInfoConfig.getUserinfo().getMerchantId() + "");
                    bundle.putString("phone", SCUserInfoConfig.getUserinfo().getUsername() + "");
                    bundle.putString("fullName", SCUserInfoConfig.getUserinfo().getFullname() + "");

                    bundle.putString("imToken", SCUserInfoConfig.getUserinfo().getImToken());
                    bundle.putString("imTokenExpireTimeSeconds", SCUserInfoConfig.getUserinfo().getImTokenExpireTimeSeconds() + "");
                    bundle.putString("imUserId", SCUserInfoConfig.getUserinfo().getImUserId());

                    Gson gson = new Gson();
                    String json = gson.toJson(SCUserInfoConfig.getUserinfo());
                    bundle.putString("userInfo", json);
                }

                bundle.putDouble("statusBarHeight", DensityUtils.px2dip(getApplicationContext(),DeviceHelper.getStatusBarHeight(getApplicationContext())));

                return bundle;
            }
        };
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FRA_SCANNING && data != null){
            String vin = data.getExtras().getString("result");

            ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
            if (reactContext == null) {
                return;
            }
            WritableMap event = Arguments.createMap();
            event.putString("vin", vin);

            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("vinScanResult", event);
        }else if (requestCode == REQUEST_SELECT_BRAND && data != null){
            ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
            if (reactContext == null) {
                return;
            }

            //车辆品牌
            ItemBean brandItem = (ItemBean) data.getExtras().getSerializable("brand");
            ItemBean seriesItem = (ItemBean) data.getExtras().getSerializable("series");
            ItemBean speciesItem = (ItemBean) data.getExtras().getSerializable("species");
            String from = data.getExtras().getString("from");
            String brandName = "";
            String seriesName = "";
            String speciesName = "";
            Long brandId = 0L;
            Long seriesId = 0L;
            Long speciesId = 0L;

            if (brandItem != null){
                brandName = brandItem.getName();
                brandId = brandItem.getId();
            }
            if (seriesItem != null){
                seriesName = seriesItem.getName();
                seriesId = seriesItem.getId();
            }
            if (speciesItem != null){
                speciesName = speciesItem.getName();
                speciesId = speciesItem.getId();
            }

            WritableMap event = Arguments.createMap();
            event.putString("brandName", brandName);
            event.putString("seriesName", seriesName);

            event.putDouble("brandId", brandId);
            event.putDouble("seriesId", seriesId);

            event.putString("speciesName", speciesName);
            event.putDouble("speciesId", speciesId);
            event.putString("from", from);

            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("selectBrandResult", event);
        }else if (requestCode == REQUEST_UPLOAD_CHECK_REPORT && data != null){
            Log.e("detectionReportPic==", "REQUEST_UPLOAD_CHECK_REPORT");
            ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
            if (reactContext == null) {
                return;
            }
            Log.e("detectionReportPic==", data.getStringExtra("detectionReportPic")+"");
            WritableMap event = Arguments.createMap();
            event.putString("detectionReportPdf", data.getExtras().getString("detectionReportPdf"));
            event.putString("detectionReportUrl", data.getExtras().getString("detectionReportUrl"));
            event.putString("detectionReportPic", data.getExtras().getString("detectionReportPic"));

            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadCheckReport", event);
        }
        else if (requestCode == REQUEST_UPLOAD_CONTRACT && data != null){
            ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
            if (reactContext == null) {
                return;
            }
            WritableMap event = Arguments.createMap();
            event.putString("contractPic", data.getExtras().getString("contractPic"));
            event.putString("contractPdf", data.getExtras().getString("contractPdf"));

            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadContract", event);
        }
        else if (requestCode == REQUEST_SELECT_FILE && data != null){//IM选择文件
            Uri uri = data.getData();
            fileUri = uri;

            String filePath = uri.getPath();
            Log.e("uriPath=",filePath);

//            imFilePath = FileUtils.getPath(this, uri);
            Log.e("filePath=", imFilePath +"");

            loadingDialog = new LoadingDialog(this,"上传中...");
            loadingDialog.show();
            getOssAuth();
        }
    }

    private void getOssAuth(){
        HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                .get(new HttpCallBack<SCAccessAuthResponse>(this) {
                    @Override
                    public void onSuccessed(SCAccessAuthResponse result) {
                        SCAccessAuthResponse response = result.getData();
                        uploadFiles(response);
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                    }
                });
    }

    private void uploadFiles(SCAccessAuthResponse auth){
        if (fileUri == null){
            if (loadingDialog != null){
                loadingDialog.dismiss();
            }
            ToastShowUtils.showFailedToast("文件上传失败");
            return;
        }
        String fileNameWithEnd = FileUtils.getFileNameByUri(this,fileUri);
        Log.e("fileNameWithEnd==",fileNameWithEnd);
        String ends = "";
        int ossType = 0;
        String[] strings = fileNameWithEnd.split("\\.");
        if (strings.length > 0){
            ends = strings[strings.length-1];
            if ("jpg".equals(ends) || "png".equals(ends) || "jpeg".equals(ends) || "webp".equals(ends) || "mp4".equals(ends)){
                ossType = SCAppConfig.OSS_IM_MEDIA;
            }else if ("mp3".equals(ends)){
                ossType = SCAppConfig.OSS_IM_SOUND;
            }else {
                ossType = SCAppConfig.OSS_IM_FILE;
            }

        }else {
            Log.e("imFilePath","获取后缀名失败");
        }

        MultiImagesUploadManager.MultiImagesUploadCallback callback =
                new MultiImagesUploadManager.MultiImagesUploadCallback() {
                    @Override
                    public void onSuccess(List<PutObjectRequest> requests) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        if (requests != null) {
//                            String[] strings = imFilePath.split("\\/");
                            String fileName = fileNameWithEnd;
                            String fileOssPath = "";
                            if (requests.size() > 0){
                                fileOssPath = SCAppConfig.IM_FILE_URL + requests.get(0).getObjectKey();
                            }
                            Log.e("fileName",fileName+"");
                            Log.e("fileOssPath",fileOssPath+"");
                            ReactContext reactContext = SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
                            if (reactContext == null) {
                                return;
                            }
                            WritableMap event = Arguments.createMap();
                            event.putString("fileName", fileName);
                            event.putString("fileOssPath", fileOssPath);
                            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadIMSuccess",event);
                        }

                    }

                    @Override
                    public void onFailure(List<PutObjectRequest> requests) {
                        ToastShowUtils.showFailedToast("文件上传失败");
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        ReactContext reactContext = SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
                        if (reactContext == null) {
                            return;
                        }
                        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadIMCancel",null);
                    }
                };

        ///storage/emulated/0/DCIM/Camera/VID_20241004_191918.mp4
        ReactContext reactContext = SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
        if (reactContext == null) {
            return;
        }
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("uploadIMStart",null);
        new MultiImagesUploadManager().startUploadIMFileByUri(fileUri, callback,
                auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                ossType,ends);
    }

    private void getMerchantConfig(){
        Map<String,Object> maps = new HashMap<>();
        maps.put("merchantId",SCUserInfoConfig.getUserinfo().getMerchantId());
        maps.put("source","app");
        HttpHelper.getInstance().appendUrl(HttpUrl.GET_MERCHANT_CONFIG).addGetParam(maps)
                .get(new HttpCallBack<MerchantConfigModel>(this) {
            @Override
            public void onSuccessed(MerchantConfigModel result) {
                if (result.getData() != null && result.getData().getAppAttr() != null){
                    SCApplication.weworkAgentId = result.getData().getAppAttr().getYeguanWeworkAgentId();
                    SCApplication.weworkSchema = result.getData().getAppAttr().getYeguanWeworkSchema();
                    SCApplication.weworkCorpId = result.getData().getAppAttr().getYeguanWeworkCorpId();
                    SCApplication.getApplication().initWWX();
                }
            }

            @Override
            public void onFailured(String errorCode, String errMsg) {

            }
        });
    }

}
